package com.example.bankend.controller;



import com.example.bankend.model.Deposit;
import com.example.bankend.model.TransactionRequest;
import com.example.bankend.service.impl.DepositService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Api(tags = "存取款交易")
@RestController
@RequestMapping("/api/deposits")
public class DepositController {
    @Autowired
    private DepositService depositService;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @ApiOperation(value = "新增存取款交易记录")
    @PostMapping("/insert")
    public int insert(@RequestBody Deposit deposit) {
        return depositService.insert(deposit);
    }

    @ApiOperation(value = "根据交易ID进行删除")
    @DeleteMapping("/delete/{savingID}")
    public int deleteByPrimaryKey(@PathVariable Integer savingID) {
        return depositService.deleteByPrimaryKey(savingID);
    }

    @ApiOperation(value = "根据交易ID进行更新")
    @PutMapping("/update/{savingID}")
    public int updateByPrimaryKey(@PathVariable Integer savingID,@RequestBody Deposit deposit) {
        System.out.println(deposit.getDescrip());
        System.out.println(deposit.getSavingName());
        deposit.setSavingID(savingID);
        return depositService.updateByPrimaryKey(deposit);
    }

    @ApiOperation(value = "根据交易ID进行查找")
    @GetMapping("/select/{savingID}")
    public Deposit selectByPrimaryKey(@PathVariable Integer savingID) {
        return depositService.selectByPrimaryKey(savingID);
    }
    @ApiOperation(value = "存取款业务逻辑")
    @PostMapping("/process") //存取款业务
    public ResponseEntity<String> processTransaction(@RequestBody TransactionRequest request) {
        try {
            // 设置会话变量
            String sql = "SET @cardID = '%s', @amount = '%s'";
            sql = String.format(sql, request.getCardID(), request.getAmount());
            jdbcTemplate.execute(sql);
            return ResponseEntity.ok(String.valueOf(depositService.processTransaction(
                    request.getCardID(),
                    request.getAmount(),
                    request.getDescrip(),
                    request.getSavingName()
            )));
        } catch (RuntimeException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        }
    }

    @ApiOperation(value = "获取所有存取款交易记录")
    @GetMapping
    public List<Deposit> selectAll() {
        return depositService.selectAll();
    }
}



